package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.ChargeContract;
import com.hzhc.entity.ZcFile;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.ZcFileMapper;
import com.hzhc.service.ZcFileService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.YytNoticeVo;
import com.hzhc.vo.ZcFileVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 97568
 * @since 2024-09-25
 */
@Service
@RequiredArgsConstructor
public class ZcFileServiceImpl extends ServiceImpl<ZcFileMapper, ZcFile> implements ZcFileService {


    @Value("${zcFile}")
    private String zcFilefolder;
    @Value("${file.zcAccessPath}")
    private String zcAccessPath;
    @Override
    public List<ZcFileVo> getZcFileList(Page<ZcFileVo> page, ZcFileVo zcFileVo) {
        IPage<ZcFileVo> iPage= baseMapper.getZcFilePage(page,zcFileVo);
        return iPage.getRecords();
    }

    @Override
    public boolean addYytNotice(ZcFile zcFile) {
        zcFile.setCreateTime(LocalDateTime.now());
        return save(zcFile);
    }

    @Override
    public Boolean delYytNotice(Long id) {
        return removeById(id);
    }
    @Override
    public ResultUtil<String> upZcfile(ZcFile vo ,MultipartFile file, String zcUploadFolder, String zcAccessPath) {
//        ZcFile zcFile  = new ZcFile();
//        BeanUtils.copyProperties(vo,zcFile);
//        boolean b = updateById(zcFile);
        if (file!= null) {
            String pathUrl = saveFiles(vo,file, zcUploadFolder, zcAccessPath);
            return ResultUtil.build(pathUrl, ResultUtilCodeEnum.SUCCESS);
        }
        return ResultUtil.fail();
    }

    @Override
    public ZcFileVo getZcFile( ZcFileVo zcFileVo) {
        ZcFileVo iPage= baseMapper.ZcFilePage(zcFileVo);
        return iPage;
    }




    public String saveFiles( ZcFile zcFile,MultipartFile files, String upfolder, String accessPath) {
        //设置日期格式
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //当地日期转换
        String dayFormat = LocalDate.now().format(formatters);
        //创建新文件：通过路径和时间
        File folder = new File(upfolder + File.separator + dayFormat);
        //文件是否存在，不存在进行创建。
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //获取文件名
        String regEx1 = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        String fileName = files.getOriginalFilename();
        String urlName = (LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + Pattern.compile(regEx1).matcher(fileName).replaceAll("").trim());
        //设置路径
        String path = folder + File.separator;
        File file = getFileByName(1, path, urlName);
        String uploadedFilePath = null; // 保存上传文件的访问路径
        try {
            // 上传文件到服务器
            files.transferTo(file);
            // 构建文件的访问路径
            uploadedFilePath = zcFilefolder+File.separator + dayFormat+File.separator +urlName;
            zcFile.setFileName(urlName);
            //拼地址
            zcAccessPath = zcAccessPath.replace("**", "").trim();
            String result =   zcAccessPath  + dayFormat + "/";
            zcFile.setFileSubfolder(result);


            save(zcFile);
            // 返回上传文件的访问路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadedFilePath;
    }

    private File getFileByName(int count, String path, String fileName) {
        File file = new File(path + fileName);
        if (file.exists()) {
            // 文件名已存在
            String prefix = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")";
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            file = getFileByName(count + 1, path, prefix + suffixName);
        }
        return file;
    }

}
